<template>
  <el-dialog
    :model-value="show"
    title="新增用户权限"
    width="1000px"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
    class="system-user-edit-dialog"
  >
    <div class="conntet-box">
      <div class="content-left">
        <div class="form-title">选择公司员工</div>
        <UserTree :activeOranize="activeOranize" @changeUser="changeUser" />
      </div>
      <div class="content-right">
        <div class="form-title">分配权限</div>
        <div class="no-data" v-if="!showList.length">请先选择公司员工</div>
        <el-form
          ref="detailFormRef"
          :model="showList"
          :rules="rules"
          label-width="70px"
          class="form-box"
          v-loading="loading || changLoading"
        >
          <div
            v-for="(item, index) in showList"
            :key="item.value"
            class="user-add-form-item"
          >
            <el-form-item
              label="姓名："
              :prop="`${index}.label`"
              style="width: 100%"
            >
              {{ item.label }}
            </el-form-item>
            <el-form-item
              label="团队："
              :prop="`${index}.group_ids`"
              :rules="{
                type: 'array',
                required: true,
                message: '请选择团队',
                trigger: 'change'
              }"
              style="width: 100%"
            >
              <el-cascader
                v-model="showList[index].group_ids"
                :options="options"
                :props="teamProps"
                :show-all-levels="false"
                :size="showList[index].group_ids?.length ? 'small' : undefined"
              />
            </el-form-item>
          </div>
        </el-form>
        <div class="pagination-box">
          <zx-pagination
            layout="total, prev, pager, next,"
            v-model:page="pages.page"
            v-model:size="pages.per_page"
            :total="dataList.length"
          />
        </div>
      </div>
    </div>
    <template #footer>
      <el-button
        type="primary"
        :loading="submitLoading"
        :disabled="!show"
        @click="submitApply"
      >
        提交
      </el-button>
      <el-button type="info" @click="handleClose">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import UserTree from './UserTree';
import {
  companyGroupAll,
  companyUserBind,
  companyUserGetGroup
} from '@/api/system';
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  activeOranize: {
    type: Object,
    default: () => {}
  }
});

const emit = defineEmits();

const teamProps = reactive({
  emitPath: false,
  checkStrictly: true,
  multiple: true,
  value: 'id',
  label: 'name',
  children: 'childs'
});

// 关闭
function handleClose() {
  emit('update:show', false);
}

// 提交
const detailFormRef = ref();
const submitLoading = ref(false);
async function submitApply() {
  try {
    await detailFormRef.value.validate();
    for (let i = 0; i < dataList.value.length; i++) {
      const item = dataList.value[i];
      if (!item.group_ids?.length) {
        return $msg.warning('团队不能为空，请检查');
      }
    }

    if (!dataList.value.length) return;

    submitLoading.value = true;
    companyUserBind({
      users: dataList.value.map(item => {
        return {
          id: item.value,
          name: item.label,
          group_ids: item.group_ids
        };
      })
    })
      .then(() => {
        $msg.success('新增用户权限成功');
        emit('success');
        handleClose();
      })
      .finally(() => {
        submitLoading.value = false;
      });
  } catch {
    $msg.warning('团队不能为空，请检查');
    console.log('用户管理-新增用户权限提交校验未通过');
  }
}

// 用户列表
const dataList = ref([]);
const changLoading = ref(false);
function changeUser(userList) {
  dataList.value = userList;

  const user_id = userList
    ?.filter(item => !item.group_ids?.length)
    ?.map(item => item.value);
  if (!user_id?.length) return;

  changLoading.value = true;
  companyUserGetGroup({ user_id })
    .then(res => {
      const resData = res.data || [];
      const resObj = {};
      resData.forEach(item => {
        resObj[item.id] = item;
      });
      user_id.forEach(item => {
        resObj[item] = resObj[item] || { id: item };
      });

      dataList.value.forEach(item => {
        const resItem = resObj[item.value];
        if (!resItem) return;
        const resGroupIds = resItem.groups?.map(item => item.id) || [];
        const activeOranizeId = props.activeOranize.id;
        const group_ids = resGroupIds;
        if (activeOranizeId && !group_ids.includes(activeOranizeId)) {
          group_ids.push(activeOranizeId);
        }
        item.group_ids = group_ids;
      });
    })
    .finally(() => {
      changLoading.value = false;
    });
}

const pages = reactive({
  page: 1,
  per_page: 5
});

const showList = computed(() => {
  const startIndex = (pages.page - 1) * pages.per_page;
  const endIndex = pages.page * pages.per_page;
  return dataList.value.slice(startIndex, endIndex);
});

// 规则
const rules = reactive({});

// 获取团队
const options = ref([]);
const loading = ref(false);
function getOptions() {
  loading.value = true;
  companyGroupAll()
    .then(res => {
      options.value = res.data || [];
      deepOptions(options.value);
    })
    .finally(() => {
      loading.value = false;
    });
}

function deepOptions(list) {
  list.forEach(item => {
    // if (!item.available) item.disabled = true;
    if (item.childs?.length) deepOptions(item.childs);
  });
}

// 初始化表单
watch(
  () => props.show,
  val => {
    if (!val) return;
    // 赋默认值
    dataList.value = [];
    pages.page = 1;
    getOptions();
  }
);
</script>

<style lang="scss" scoped>
.conntet-box {
  display: flex;
  height: 100%;
}
.content-left {
  width: 350px;
  display: flex;
  flex-direction: column;
  height: 100%;
  :deep(.organize-tree) {
    flex: 1;
  }
}
.content-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  :deep(.el-form) {
    overflow-y: auto;
  }
}
.user-add-form-item {
  width: 100%;
  border: 1px dashed #dfdfdf;
  margin-top: 15px;
  padding: 10px 15px 5px;
  box-sizing: border-box;
  &:first-child {
    margin-top: 10px;
  }
}
.no-data {
  color: #aaa;
  text-align: center;
  line-height: 50px;
  border: 1px dashed #dfdfdf;
  margin-top: 10px;
}
.pagination-box {
  margin-top: 15px;
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
.form-box {
  display: block;
}
</style>

<style>
.system-user-edit-dialog .el-dialog__body {
  height: 65vh;
}
</style>
